<template>
  <q-dialog seamless v-model="visible" position="top">
    <div class="q-pa-sm blur">
      <div class="flex justify-center q-gutter-sm">
        <q-btn
          class="text-bold"
          label="结束定位"
          color="secondary"
          icon-right="location_off"
          @click="close"
        />
        <q-btn
          class="text-bold"
          :label="isLocation ? '当前模式：修改位置' : '当前模式：修改方向'"
          color="secondary"
          :icon-right="isLocation ? 'replay' : 'shuffle'"
          @click="changeMode()"
        />
      </div>
    </div>
  </q-dialog>
</template>

<script>
import { ref, inject, watch } from "vue";

export default {
  name: "PointRelocate",
  setup(props, context) {
    const visible = ref(false);
    const pixiMap = inject("pixiMap");
    const pointList = inject("pointList");
    const pointId = ref();
    const point = ref({});
    const isLocation = ref(true);
    // 临时坐标
    const tempPose = ref({});
    // 修改模式
    function changeMode() {
      isLocation.value = !isLocation.value;
    }
    // 模式的监听
    watch(isLocation, (value) => {
      // 重定位关闭
      pixiMap.pointLocation = false;
      // 方向定位关闭
      pixiMap.changePointDirection = false;
      if (value) {
        pixiMap.pointLocation = true;
      } else {
        pixiMap.changePointDirection = true;
      }
    });
    function show(id) {
      isLocation.value = true;
      pointId.value = id;
      // 获取当前的对象
      pointList.value.forEach((item) => {
        if (item.id === id) {
          point.value = item;
        }
      });
      // 重定位
      pixiMap.changePoint = (pos) => {
        tempPose.value = pos;
        point.value.pose.position.x = pos.x;
        point.value.pose.position.y = pos.y;
        pixiMap.drawRail();
      };
      // 方向定位
      pixiMap.PointDirection = (pos) => {
        const theta = Math.atan2(
          pos.y - point.value.pose.position.y,
          pos.x - point.value.pose.position.x
        );
        point.value.pose.orientation.z = Math.sin(theta / 2);
        point.value.pose.orientation.w = Math.cos(theta / 2);
        pixiMap.drawRail();
      };
      visible.value = true;
      pixiMap.pointLocation = true;
    }
    // 监听组件关闭后吧定位关闭
    watch(visible, (value) => {
      if (!value) {
        pixiMap.pointLocation = false;
        pixiMap.changePointDirection = false;
      }
    });
    function close() {
      visible.value = false;
      context.emit("update");
    }
    return {
      visible,
      isLocation,
      show,
      changeMode,
      close,
    };
  },
};
</script>

<style scoped></style>
